package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.FormatUtil;
import com.ruoyi.system.domain.Sub;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SubinfoMapper;
import com.ruoyi.system.domain.Subinfo;
import com.ruoyi.system.service.ISubinfoService;
import org.springframework.util.StringUtils;

/**
 * 数据回显值Service业务层处理
 * 
 * @author yaozh
 * @date 2024-03-14
 */
@Service
public class SubinfoServiceImpl implements ISubinfoService 
{
    private static final Logger log = LoggerFactory.getLogger(SubinfoServiceImpl.class);
    @Autowired
    private SubinfoMapper subinfoMapper;

    /**
     * 查询数据回显值
     * 
     * @param id 数据回显值主键
     * @return 数据回显值
     */
    @Override
    public Subinfo selectSubinfoById(Long id, String dbName)
    {
        return subinfoMapper.selectSubinfoById(id, dbName);
    }

    /**
     * 查询数据回显值列表
     * 
     * @param subinfo 数据回显值
     * @return 数据回显值
     */
    @Override
    public List<Subinfo> selectSubinfoList(Subinfo subinfo, String dbName)
    {
        return subinfoMapper.selectSubinfoList(subinfo, dbName);
    }

    /**
     * 增加子阈值
     * @param dBname
     * @param subinfo
     * @return
     */
    @Override
    public int saveObject(String dBname, Subinfo subinfo) {
        int rows=0;
        try {
            rows=subinfoMapper.insertObject(dBname,subinfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("保存失败");
        }
        return rows;
    }

    @Override
    public int updateObjectBySubIdAndValue(String dBname, Subinfo subinfo) {
        int rows=0;
        try {
            rows=subinfoMapper.updateObjectBySubIdAndValue(dBname,subinfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("更新失败");
        }
        return rows;
    }

    /**
     * 新增数据回显值
     * 
     * @param subinfo 数据回显值
     * @return 结果
     */
    @Override
    public int insertSubinfo(Subinfo subinfo, String dbName)
    {
        return subinfoMapper.insertSubinfo(subinfo, dbName);
    }

    /**
     * 修改数据回显值
     * 
     * @param subinfo 数据回显值
     * @return 结果
     */
    @Override
    public int updateSubinfo(Subinfo subinfo, String dbName)
    {
        return subinfoMapper.updateSubinfo(subinfo, dbName);
    }

    /**
     * 批量删除数据回显值
     * 
     * @param ids 需要删除的数据回显值主键
     * @return 结果
     */
    @Override
    public int deleteSubinfoByIds(Long[] ids, String dbName)
    {
        return subinfoMapper.deleteSubinfoByIds(ids, dbName);
    }

    /**
     * 删除数据回显值信息
     * 
     * @param id 数据回显值主键
     * @return 结果
     */
    @Override
    public int deleteSubinfoById(Long id, String dbName)
    {
        return subinfoMapper.deleteSubinfoById(id, dbName);
    }

    @Override
    public String importSubInfo(List<Subinfo> subInfoList, Boolean isUpdateSupport, String operaName, String dbName){
        if (subInfoList == null || subInfoList.size() == 0)
        {
            throw new ServiceException("导入项目设备属性回显数值不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Subinfo subInfo : subInfoList)
        {
            try{
                // 验证是否存在
                String value = subInfo.getValue();
                Long subId = subInfo.getSubid();
                Subinfo tempSubInfo = subinfoMapper.selectSubInfoBySubIdAndValue(subId,value,dbName);
                if (tempSubInfo == null)
                {
                    subInfo.setCreateBy(operaName);
                    subinfoMapper.insertSubinfo(subInfo,dbName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、属性回显数值定义名称 " + subInfo.getText() + "、属性回显数值定义的值 " + subInfo.getValue() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    subInfo.setId(tempSubInfo.getId());
                    subInfo.setUpdateBy(operaName);
                    subinfoMapper.updateSubinfo(subInfo,dbName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、属性回显数值定义名称 " + subInfo.getText() + "、属性回显数值定义的值 " + subInfo.getValue() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、属性回显数值定义名称 " + subInfo.getText() + "、属性回显数值定义的值 " + subInfo.getValue() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、属性回显数值定义名称 " + subInfo.getText() + "、属性回显数值定义的值 " + subInfo.getValue() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<Subinfo> findAllObject(@Param("dBname") String dBname){
        return subinfoMapper.findAllObject(dBname);
    }

    @Override
    public Map<String,Long> getRegSubInfoMapList(String dbName,List<Subinfo> subInfoList){
        Map<String,Long> regSubInfoMap = new HashMap<>();
        if(subInfoList == null){
            return regSubInfoMap;
        }

        Map<Long,List<Subinfo>> subInfoMap = subInfoList.stream().collect(Collectors.groupingBy(Subinfo::getSubid));
        if(subInfoMap == null){
            return regSubInfoMap;
        }

        Iterator iterator = subInfoMap.keySet().iterator();
        while (iterator.hasNext()){
            Long subId = (Long)iterator.next();
            List<Subinfo> tempSubInfoList = subInfoMap.get(subId);
            if(tempSubInfoList == null || tempSubInfoList.size() == 0){
                continue;
            }
            //排序
            Collections.sort(tempSubInfoList, new Comparator<Subinfo>() {
                @Override
                public int compare(Subinfo o1, Subinfo o2) {
                    String value1 = o1.getValue() + o1.getText();//排序方式要和getRegSubInfoMapList里面的排序保持一致，都是value + text，然后再排序，否则返回的key不一致，导致误报阈值不存在
                    String value2 = o2.getValue() + o2.getText();//排序方式要和getRegSubInfoMapList里面的排序保持一致，都是value + text，然后再排序，否则返回的key不一致，导致误报阈值不存在
                    return value1.compareTo(value2);
                }
            });

            String keyOne = "";
            String keyTwo = "";
            String keyThree = "";
            String keyFour = "";
            String keyFive = "";
            String keySix = "";
            String keySeven = "";
            String keyEight = "";
            for(Subinfo subInfo : tempSubInfoList){
                keyOne = keyOne + subInfo.getValue() + ":" + subInfo.getText() + "；";
                keyTwo = keyTwo + subInfo.getValue() + "：" + subInfo.getText() + "；";
                keyThree = keyThree + subInfo.getValue() + "：" + subInfo.getText() + ";";
                keyFour = keyFour + subInfo.getValue() + ":" + subInfo.getText() + ";";
                keyFive = keyFive + subInfo.getValue() + subInfo.getText() + "；";
                keySix = keySix + subInfo.getValue() + subInfo.getText() + ";";
                keySeven = keySeven + subInfo.getValue() + "=" + subInfo.getText() + "；";
                keyEight = keyEight + subInfo.getValue() + "=" + subInfo.getText() + ";";
            }
            if(StringUtils.hasLength(keyOne)){
                regSubInfoMap.put(keyOne,subId);
                regSubInfoMap.put(keyTwo,subId);
                regSubInfoMap.put(keyThree,subId);
                regSubInfoMap.put(keyFour,subId);
                regSubInfoMap.put(keyFive,subId);
                regSubInfoMap.put(keySix,subId);
                regSubInfoMap.put(keySeven,subId);
                regSubInfoMap.put(keyEight,subId);
            }
        }
        return regSubInfoMap;
    }

    public String getSubInfoKey(String tagDesc){
        String key = "";
        if(StringUtils.hasLength(tagDesc) && (tagDesc.contains("；") || tagDesc.contains(";"))){
            if(tagDesc.contains("；")){
                String[] array = tagDesc.split("；");
                String[] array2 = new String[array.length];
                int i = 0;
                for(String text : array){
                    if(StringUtils.hasLength(text)){
                        String a = remove(text);
                        array2[i] = a;
                        i++;
                    }
                }
                ArrayList<String> list = new ArrayList<>(Arrays.asList(array2));
                Collections.sort(list);//排序方式要和getRegSubInfoMapList里面的排序保持一致，都是value + text，然后再排序，否则返回的key不一致，导致误报阈值不存在
                for(String item : list){
                    key = key + item + "；";
                }
            }else if(tagDesc.contains(";")){
                String[] array = tagDesc.split(";");
                String[] array2 = new String[array.length];
                int i = 0;
                for(String text : array){
                    if(StringUtils.hasLength(text)){
                        String a = remove(text);
                        array2[i] = a.trim();
                        i++;
                    }
                }
                ArrayList<String> list = new ArrayList<>(Arrays.asList(array2));
                Collections.sort(list);//排序方式要和getRegSubInfoMapList里面的排序保持一致，都是value + text，然后再排序，否则返回的key不一致，导致误报阈值不存在
                for(String item : list){
                    key = key + item + ";";
                }
            }
        }
        return key;
    }

    @Override
    public List<Subinfo> getSubInfoFromSubIdKey(Long subId, String subIdKey) {
        List<Subinfo> list = new ArrayList<>();
        String[] array = null;
        if(StringUtils.hasLength(subIdKey) && (subIdKey.contains("；") || subIdKey.contains(";"))){
            if(subIdKey.contains("；")){
                array = subIdKey.split("；");
            }else if(subIdKey.contains(";")){
                array = subIdKey.split(";");
            }
        }
        for(String item : array){
            //item格式如0停止，或者1开启，9XXX，10ccc，12XXX 等等
            int len = FormatUtil.getLenOfNumber(item);
            String value = item.substring(0,len);
            String text = item.substring(len);
            Subinfo subinfo = new Subinfo();
            subinfo.setSubid(subId);
            subinfo.setValueType("1");
            subinfo.setValue(value);
            subinfo.setText(text);
            list.add(subinfo);
        }
        return list;
    }

    private String remove(String text){
        String a = text;
        a = a.contains("=") && !a.startsWith("=") && !a.endsWith("=") ? a.substring(0,a.indexOf("=")).trim() + a.substring(a.indexOf("=") + 1).trim() : a.trim();//
        a = a.contains("：") && !a.startsWith("：") && !a.endsWith("：") ? a.substring(0,a.indexOf("：")).trim() + a.substring(a.indexOf("：") + 1).trim() : a.trim();//
        a = a.contains(":") && !a.startsWith(":") && !a.endsWith(":") ? a.substring(0,a.indexOf(":")).trim() + a.substring(a.indexOf(":") + 1).trim() : a.trim();//
        a = a.contains("-") && !a.startsWith("-") && !a.endsWith("-") ? a.substring(0,a.indexOf("-")).trim() + a.substring(a.indexOf("-") + 1).trim() : a.trim();//
        return a;//返回是value + text
    }
}
